<template>
  <div>
    <el-dialog
      title="权限分配"
      :visible="dialogVisible"
      width="40%"
      @close="close"
      @open="open"
    >
      <!-- show-checkbox 显示复选框
    node-key="id" 配置默认选中时使用
    default-checked-keys 默认选中的节点
    default-expand-all 是否默认展开所有的节点 -->
      <el-tree
        ref="tree"
        :data="list"
        :props="defaultProps"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionList, assignPermission, getRoleById } from '@/api'

import { findChildren } from '@/utils'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: [],
      defaultProps: {
        label: 'name'
      }
    }
  },
  methods: {
    close() {
      this.$emit('close')
    },
    // 打开弹窗
    async open() {
      const res = await getPermissionList()
      // 后端告诉的根节点的pid设置为0
      this.list = findChildren(res.data, '0')
      // 数据组件的数据回显
      const { data } = await getRoleById(this.roleId)
      // setCheckedKeys 通过keys设置勾选节点 接受一个数组 数组中是需要选中一个节点的node-key 的值
      this.$refs.tree.setCheckedKeys(data.permIds)
    },
    async submit() {
      await assignPermission({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('修改权限成功')
      this.close()
    }
  }
}
</script>

<style>

</style>
